//
//  ViewController.m
//  读写安全
//
//  Created by 崔博 on 2018/9/10.
//  Copyright © 2018年 崔博. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong) dispatch_semaphore_t sem;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.sem = dispatch_semaphore_create(1);
    for (int i = 0; i < 5; i++) {
        [[[NSThread alloc] initWithTarget:self selector:@selector(read) object:nil] start];
        [[[NSThread alloc] initWithTarget:self selector:@selector(write) object:nil] start];
    };
    
}


- (void)read
{
    dispatch_semaphore_wait(self.sem, DISPATCH_TIME_FOREVER);
    NSLog(@"%s",__func__);
    dispatch_semaphore_signal(self.sem);
}
- (void)write
{
    dispatch_semaphore_wait(self.sem, DISPATCH_TIME_FOREVER);
    NSLog(@"%s",__func__);
    dispatch_semaphore_signal(self.sem);
}
@end
